import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react';
import { Button } from 'antd';
import { SendOutlined, CopyOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import UniversalCard from './UniversalCard';

// 简单的节流工具函数
const throttle = <T extends (...args: any[]) => void>(func: T, delay: number): T => {
  let lastCall = 0;
  return ((...args: Parameters<T>) => {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      func(...args);
    }
  }) as T;
};

// MarkdownRenderer组件，支持[CARD:xxx]自定义渲染 - 使用React.memo优化性能
const MarkdownRenderer = React.memo(({ content }: { content: string }) => {
  // 支持 [CARD:基金名称-时间范围-累计收益率走势]
  const CARD_TOKEN = /\[CARD:([^\]]+)\]/g;

  // 生成稳定的key，避免重复渲染
  const contentHash = useMemo(() => {
    let hash = 0;
    for (let i = 0; i < content.length; i++) {
      const char = content.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash;
    }
    return hash.toString(36);
  }, [content]);

  function renderWithCard(node: any, parentKey: string = ''): any {
    if (typeof node === 'string') {
      const parts = [];
      let lastIndex = 0;
      let match;
      let matchIndex = 0;
      while ((match = CARD_TOKEN.exec(node))) {
        if (match.index > lastIndex) {
          parts.push(node.slice(lastIndex, match.index));
        }
        const cardContent = match[1];
        const cardKey = `universalcard_${contentHash}_${matchIndex}_${cardContent}`;
        parts.push(
          <UniversalCard key={cardKey} cardContent={cardContent} />
        );
        lastIndex = match.index + match[0].length;
        matchIndex++;
      }
      if (lastIndex < node.length) {
        parts.push(node.slice(lastIndex));
      }
      return parts.length === 1 ? parts[0] : <>{parts}</>;
    } else if (Array.isArray(node)) {
      return node.map((child, idx) => (
        <React.Fragment key={`${parentKey}_${idx}`}>
          {renderWithCard(child, `${parentKey}_${idx}`)}
        </React.Fragment>
      ));
    } else if (React.isValidElement(node)) {
      return React.cloneElement(node, (node as any).props, renderWithCard((node as any).props.children, parentKey));
    }
    return node;
  }

  return (
    <ReactMarkdown
      remarkPlugins={[remarkGfm]}
      components={{
        p({ children }) {
          const rendered = renderWithCard(children);
          const isAllString = (nodes: any): boolean => {
            if (typeof nodes === 'string' || nodes == null) return true;
            if (Array.isArray(nodes)) return nodes.every(isAllString);
            return false;
          };
          if (isAllString(rendered)) {
            return <p>{rendered}</p>;
          } else {
            return <div>{rendered}</div>;
          }
        },
        li({ children }) {
          return <li>{renderWithCard(children)}</li>;
        },
        span({ children }) {
          return <span>{renderWithCard(children)}</span>;
        },
      }}
    >
      {content}
    </ReactMarkdown>
  );
});

// 段落内容检查器组件，用于检测渲染后的内容是否为空
function SegmentContentChecker({ 
  content, 
  onValidityChange 
}: { 
  content: string;
  onValidityChange: (isValid: boolean) => void;
}) {
  const contentRef = useRef<HTMLDivElement>(null);
  const [isValid, setIsValid] = useState(true);
  const [isUpdating, setIsUpdating] = useState(false); // 防止状态循环更新

  // 根据内容类型优化Observer配置
  const observerConfig = useMemo(() => {
    const hasCardContent = content.includes('[CARD:');
    const hasComplexMarkdown = content.includes('![') || content.includes('](') || content.includes('```');
    
    if (hasCardContent || hasComplexMarkdown) {
      // 复杂内容需要深度监听
      return { childList: true, subtree: true, characterData: true };
    } else {
      // 简单文本只监听基本变化
      return { childList: true, characterData: true };
    }
  }, [content]);

  // 内容检查函数，添加异常处理
  const checkContent = useCallback(() => {
    try {
      if (!contentRef.current) return;

      // 获取渲染后的文本内容，去除空白字符
      const textContent = contentRef.current.textContent?.trim() || '';
      
      // 检查是否有实际的DOM内容（除了文本，还可能有其他元素）
      const hasElements = contentRef.current.children.length > 0;
      
      // 检查是否有有效内容：
      // 1. 有非空文本内容，或
      // 2. 有子元素且不是空的卡片容器
      let hasValidContent = false;
      
      if (textContent.length > 0) {
        hasValidContent = true;
      } else if (hasElements) {
        // 检查子元素是否包含有效内容
        const childElements = Array.from(contentRef.current.children);
        hasValidContent = childElements.some(element => {
          try {
            const elementText = element.textContent?.trim() || '';
            const hasVisibleContent = elementText.length > 0 || element.querySelector('img, canvas, svg');
            return hasVisibleContent;
          } catch (error) {
            // 如果检查单个元素失败，默认认为有效
            console.warn('Failed to check element content:', error);
            return true;
          }
        });
      }

      const validity = hasValidContent;
      
      // 防止状态循环更新
      if (validity !== isValid && !isUpdating) {
        setIsUpdating(true);
        setIsValid(validity);
        onValidityChange(validity);
        
        // 下一个tick清除更新标志
        setTimeout(() => setIsUpdating(false), 0);
      }
    } catch (error) {
      console.warn('Content validity check failed:', error);
      // 降级处理：假定内容有效，避免页面崩溃
      if (!isUpdating) {
        setIsUpdating(true);
        setIsValid(true);
        onValidityChange(true);
        setTimeout(() => setIsUpdating(false), 0);
      }
    }
  }, [content, isValid, onValidityChange, isUpdating]);

  // 节流处理的检查函数，100ms内最多执行一次
  const throttledCheckContent = useMemo(
    () => throttle(checkContent, 100),
    [checkContent]
  );

  useEffect(() => {
    let observer: MutationObserver | null = null;
    let checkTimeout: NodeJS.Timeout | null = null;

    try {
      // 使用节流处理的MutationObserver
      observer = new MutationObserver((mutations) => {
        // 只有当mutations实际改变了内容时才检查
        const hasContentChange = mutations.some(mutation => 
          mutation.type === 'childList' || 
          mutation.type === 'characterData' ||
          (mutation.type === 'attributes' && mutation.attributeName === 'src')
        );
        
        if (hasContentChange) {
          throttledCheckContent();
        }
      });
      
      if (contentRef.current) {
        observer.observe(contentRef.current, observerConfig);
      }

      // 初始检查，延迟执行避免影响初始渲染
      checkTimeout = setTimeout(() => {
        throttledCheckContent();
      }, 50);

    } catch (error) {
      console.warn('Failed to initialize content checker:', error);
      // 降级处理：假定内容有效
      if (!isUpdating) {
        setIsUpdating(true);
        setIsValid(true);
        onValidityChange(true);
        setTimeout(() => setIsUpdating(false), 0);
      }
    }

    return () => {
      try {
        if (observer) {
          observer.disconnect();
        }
        if (checkTimeout) {
          clearTimeout(checkTimeout);
        }
      } catch (error) {
        console.warn('Failed to cleanup content checker:', error);
      }
    };
  }, [content, observerConfig, throttledCheckContent, onValidityChange, isUpdating]);

  return (
    <div ref={contentRef} style={{ visibility: 'hidden', position: 'absolute', top: -9999, pointerEvents: 'none' }}>
      <MarkdownRenderer content={content} />
    </div>
  );
}

// 组件属性接口定义
export interface SmartSegmentedMessageRendererProps {
  content: string;
  itemId: string;
  onSendSegment: (segment: string) => void;
  onCopySegment: (segment: string) => void;
  className?: string;
}

// 智能分割消息渲染器组件，支持内容有效性检查
export default function SmartSegmentedMessageRenderer({ 
  content, 
  itemId,
  onSendSegment, 
  onCopySegment,
  className = ''
}: SmartSegmentedMessageRendererProps) {
  // 判断段落是否只包含卡片占位符
  const isOnlyCardPlaceholder = useCallback((segment: string): boolean => {
    if (!segment || !segment.trim()) return false;
    
    // 检查是否只是卡片占位符格式 [CARD:...]
    const trimmedSegment = segment.trim();
    const cardPattern = /^\[CARD:[^\]]+\]$/;
    
    return cardPattern.test(trimmedSegment);
  }, []);

  // 分割消息
  const messageParts = useMemo(() => {
    try {
      return content
        .split(/\[DIVIDER\]|\n\n+/)
        .map(part => part.trim())
        .filter(part => part.length > 0);
    } catch (error) {
      console.warn('Failed to split message content:', error);
      // 降级处理：返回原始内容
      return [content];
    }
  }, [content]);

  // 分析哪些段落需要检查器，哪些可以直接渲染
  const segmentInfo = useMemo(() => {
    return messageParts.map((part, index) => ({
      part,
      index,
      needsChecker: isOnlyCardPlaceholder(part)
    }));
  }, [messageParts, isOnlyCardPlaceholder]);

  // 只跟踪需要检查器的段落的有效性
  const [segmentValidities, setSegmentValidities] = useState<{[key: number]: boolean}>({});

  // 处理段落有效性变化，添加异常处理
  const handleValidityChange = useCallback((index: number, isValid: boolean) => {
    try {
      setSegmentValidities(prev => ({
        ...prev,
        [index]: isValid
      }));
    } catch (error) {
      console.warn('Failed to update segment validity:', error);
    }
  }, []);

  // 初始化需要检查器的段落的有效性状态
  useEffect(() => {
    try {
      const initialValidities: {[key: number]: boolean} = {};
      segmentInfo.forEach(({ index, needsChecker }) => {
        if (needsChecker) {
          initialValidities[index] = true; // 默认为有效，等待检查器验证
        }
      });
      setSegmentValidities(initialValidities);
    } catch (error) {
      console.warn('Failed to initialize segment validities:', error);
    }
  }, [segmentInfo]);

  // 过滤出需要渲染的段落
  const segmentsToRender = useMemo(() => {
    try {
      return segmentInfo.filter(({ index, needsChecker }) => {
        if (!needsChecker) {
          // 不需要检查器的段落直接渲染
          return true;
        } else {
          // 需要检查器的段落，根据检查结果决定是否渲染
          return segmentValidities[index] !== false;
        }
      });
    } catch (error) {
      console.warn('Failed to filter segments to render:', error);
      // 降级处理：返回所有段落信息
      return segmentInfo;
    }
  }, [segmentInfo, segmentValidities]);

  // 如果所有段落都无效，不渲染任何内容
  if (segmentsToRender.length === 0) {
    return null;
  }

  // 将有序列表转换为纯文本格式的函数
  const convertOrderedListToPlainText = (content: string): string => {
    // 将markdown有序列表格式转换为纯文本
    // 例如："1. 文本" -> "1. 文本" (保持原样，不让接收端解析为HTML列表)
    return content
      // 移除可能导致HTML列表解析的markdown语法
      .replace(/^\s*(\d+)\.\s+/gm, '$1. ') // 确保格式统一为 "数字. 内容"
      // 如果需要，可以添加更多转换逻辑
  };

  // 安全的按钮点击处理
  const handleSendClick = useCallback((part: string) => {
    try {
      // 将有序列表转换为纯文本格式后发送
      const plainTextContent = convertOrderedListToPlainText(part);
      console.log('🔄 原始内容:', part);
      console.log('📤 发送内容:', plainTextContent);
      onSendSegment(plainTextContent);
    } catch (error) {
      console.error('Failed to send segment:', error);
    }
  }, [onSendSegment]);

  const handleCopyClick = useCallback((part: string) => {
    try {
      onCopySegment(part);
    } catch (error) {
      console.error('Failed to copy segment:', error);
    }
  }, [onCopySegment]);

  return (
    <div className={`space-y-3 ${className}`}>
      {/* 只为需要检查的段落创建隐藏的内容检查器 */}
      {segmentInfo
        .filter(({ needsChecker }) => needsChecker)
        .map(({ part, index }) => (
          <SegmentContentChecker
            key={`${itemId}-checker-${index}`}
            content={part}
            onValidityChange={(isValid) => handleValidityChange(index, isValid)}
          />
        ))
      }
      
      {/* 只渲染需要渲染的段落 */}
      {segmentsToRender.map(({ part, index }) => {
        // 统一渲染所有有效内容，包含操作按钮
        return (
          <div key={`${itemId}-part-${index}`} className="flex justify-start">
            <div className="max-w-xs px-3 py-2 rounded-lg bg-white text-gray-800 border border-gray-200">
              <div className="text-sm prose prose-sm max-w-none">
                <MarkdownRenderer content={part} />
              </div>
              <div className="flex gap-1 mt-2">
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleSendClick(part)}
                  icon={<SendOutlined />}
                >
                  发送
                </Button>
                <Button
                  size="small"
                  onClick={() => handleCopyClick(part)}
                  icon={<CopyOutlined />}
                >
                  复制
                </Button>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// 导出内部组件以便在其他地方使用
export { SegmentContentChecker, MarkdownRenderer }; 